package android.slc.appbase.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author slc
 * @date 2024/5/31
 **/
public class AutoServiceUtils {

    public static <S> S load(Class<S> service) {
        return load(service, item -> true);
    }

    public static <S> S load(Class<S> service, Predicate<S> predicate) {
        Iterator<S> iterator = ServiceLoader.load(service).iterator();
        if (iterator.hasNext()) {
            S item = iterator.next();
            if (predicate.evaluate(item)) {
                return item;
            }
        }
        return null;
    }

    public static <S> List<S> loadMultiple(Class<S> service) {
        Iterator<S> iterator = ServiceLoader.load(service).iterator();
        List<S> resultList = new ArrayList<>();
        while (iterator.hasNext()) {
            resultList.add(iterator.next());
        }
        return resultList;
    }

    public interface Predicate<E> {
        boolean evaluate(E item);
    }
}
